/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable prefer-destructuring */
import React, { useEffect } from 'react';
import { Button, Form, message } from 'antd';
import { useSelector } from 'dva';
import { getLStorage, setLStorage } from '@/utils/utils';
import { useDebounceFn } from 'ahooks';
import ZoneSelect from '../ZoneSelect';

const DispatchPianqu = Form.create()(({ form, onChange, type }) => {
  const { getFieldDecorator, getFieldsValue, setFieldsValue } = form;
  const { user_info } = useSelector(({ user }) => user.currentUser);
  const { gp_area_ids = [], inn_area_ids = [], phone, area_ids } = user_info;
  const isCompany = area_ids == '*';
  const { area_id } = getFieldsValue();

  const storageKey = `KB_${type.toUpperCase()}_AREA_${phone}`;

  const { run } = useDebounceFn(
    () => {
      const area_id_l = getLStorage(storageKey);
      if (area_id_l != area_id) {
        message.success('切换成功！')
        setLStorage(storageKey, area_id);
        onChange && onChange(area_id);
      }
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  useEffect(
    () => {
      let initZone = getLStorage(storageKey);
      if (type == 'gp' && !gp_area_ids.includes(initZone)) {
        initZone = isCompany ? '0' : gp_area_ids[0];
      }
      if (type == 'inn' && !inn_area_ids.includes(initZone)) {
        initZone = isCompany ? '0' : [...inn_area_ids].reverse().join(',');
      }
      if (initZone) {
        setFieldsValue({
          area_id: initZone,
        });
      }
    },
    [type, isCompany],
  );

  // 未开启共配独立权限
  if (type == 'gp' && gp_area_ids.length == 0) {
    return null;
  }
  // 未开启驿站独立权限
  if (type == 'inn' && inn_area_ids.length == 0) {
    return null;
  }

  return (
    <Form layout="inline">
      <Form.Item label="片区">{getFieldDecorator('area_id')(<ZoneSelect type={type} />)}</Form.Item>
      <Form.Item>
        <Button type="primary" onClick={run}>
          切换
        </Button>
      </Form.Item>
    </Form>
  );
});

/**
 * 片区切换
 *  */
const Index = ({ onChange, type }) => {
  const { key } = useSelector(({ setting }) => setting.options);
  const { area_ids = '' } = useSelector(({ user }) => user.currentUser.user_info);
  // 非新零售都不展示
  if (key != 'yz') {
    return null;
  }

  // 如果存在片区开启驿站片区管理，并且登录的账号为公司层级账号或者管理多个片区层级账号，则显示片区切换功能
  if ((area_ids.length == 1 && area_ids != '*') || !area_ids) {
    return null;
  }

  return <DispatchPianqu onChange={onChange} type={type} />;
};

export default Index;
